'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: 11_study_function_call_with_roolback.py
* @Time: 2025/11/3
* @All Rights Reserve By Brtc
'''
from typing import Any

import dotenv
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
dotenv.load_dotenv()
@tool
def complex_tool(int_arg:int, float_arg:float) -> int:
    """使用复杂工具进行复杂计算"""
    print("int arg:", int_arg)
    print("float arg:", float_arg)
    return int(int_arg*float_arg)
def try_except_tool(tool_args:dict, config:RunnableConfig) -> Any:
    try:
        return complex_tool.invoke(tool_args, config)
    except Exception as e:
        return f"调用工具出错， 参数是:{tool_args},错误是:{str(e)}"
# 1、创建模型并绑定工具
llm = ChatOpenAI(model="gpt-3.5-turbo-16kllll", temperature=0).bind_tools([complex_tool])
better_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0).bind_tools([complex_tool])
#2、创建链并执行工具
better_chain = better_llm| (lambda msg:msg.tool_calls[0]["args"])|complex_tool
chain = (llm | (lambda msg:msg.tool_calls[0]["args"])|complex_tool).with_fallbacks([better_chain])
#3、调用链
print(chain.invoke("请使用复杂工具, 对应3个参数分别为5和2.1"))

